<template xmlns="http://www.w3.org/1999/html">
  <div id="chat-app">
    <!-- 左侧导航栏 -->
    <aside class="sidebar">
      <h2 class="sidebar-title">导航</h2>
      <ul class="nav-list">
        <li
            v-for="(window, index) in windows"
            :key="index"
            :class="{ active: activeWindow === index }"
            @click="selectWindow(index)"
            class="nav-item"
        >
          <div class="nav-item-content">
            <span class="nav-item-name">{{ window.name }}</span>
            <span class="nav-item-time">{{ window.play_time }}</span>
          </div>
        </li>
      </ul>
      <router-link to="/" class="home-link">返回主页</router-link>
    </aside>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 顶部标题和按钮 -->
      <header class="header">
        <h1 class="header-title">{{ windows[activeWindow].name }}</h1>
      </header>

      <!-- 聊天窗口内容 -->
      <main class="chat-window">

        <!-- 添加加载动画 -->
        <a-spin v-if="isLoading" class="loading-spinner" size="large" />

        <div v-if="!windows[activeWindow]?.conversation || windows[activeWindow].conversation.length === 0" class="examples">
          <h2>开启一段新的文字冒险吧！</h2>
          <button v-for="(example, index) in examples" :key="index" class="example-button">
            {{ example }}
          </button>
        </div>

        <div v-else class="chat-log">
          <div
              v-for="(conv, idx) in windows[activeWindow].conversation"
              :key="idx"
              :class="['message', conv.speaker]"
          >
            <div class="avatar-container">
              <img :src="conv.speaker === 'human' ? userInfo.avatar || defaultAvatar : aiAvatar" alt="Avatar" class="avatar">
              <span class="nickname">{{ conv.speaker === 'human' ? userInfo.username : 'AI' }}</span>
            </div>
            <p class="message-text">{{ conv.speech }}</p>
          </div>
        </div>
      </main>

      <!-- 输入框 -->
      <footer class="input-area">
        <textarea v-model="message" placeholder="请输入消息..." class="input-box"></textarea>
        <button @click="sendMessage" class="send-button">
          <svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 24 24">
            <line x1="22" y1="2" x2="11" y2="13"></line>
            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
          </svg>
        </button>
      </footer>
    </div>
  </div>
</template>

<script>

// 引入AIChat.js里的接口函数
import {
  askAIService,
  getConversationMessagesService,
  getUserConversationsService,
  initializeScriptService
} from "@/api/AIChat";
import defaultAvatar from "@/assets/default-avatar.png";
import aiAvatar from "@/assets/ai-avatar.jpg";
import request from "@/utils/request";
import Navbar from "@/components/Navbar.vue";
import {getScriptByIdService} from "@/api/script";

export default {
  name: "ChatInterface",
  components: {Navbar},
  data() {
    return {
      activeWindow: 0,
      message: '',
      windows: [{id:0, name: '欢迎来到AI冒险世界', conversation: [] }],
      examples: [],
      scriptId: 0,
      defaultConversationId: 0,
      userInfo: {id:0, username: 'Player', avatar: defaultAvatar , role: 'user' },  // 默认用户信息
      defaultAvatar: defaultAvatar,
      aiAvatar: aiAvatar,
      isLoading: true,
    };
  },
  //加载基本数据
  async mounted() {
    this.isLoading = true;
    // 从路由参数中获取 scriptId 和 defaultConversationId
    this.scriptId = parseInt(this.$route.params.scriptId);
    this.defaultConversationId = parseInt(this.$route.params.conversationId);
    // 获取从 localStorage 中存储的 userInfo
    let curUserInfo = localStorage.getItem('userInfo');
    if (curUserInfo) {
      curUserInfo = JSON.parse(curUserInfo);
      if (curUserInfo.avatar) {
        try {
          // 使用 request 工具类请求头像
          const response = await request.get(curUserInfo.avatar, {
            responseType: "blob"
          });
          // 将 Blob 数据转换为 URL
          curUserInfo.avatar = URL.createObjectURL(response);
        } catch (error) {
          console.error("Failed to load avatar image:", error);
          curUserInfo.avatar = '';
        }
      }
      this.userInfo = curUserInfo;
    } else {
      alert('请重新登录。');
      this.$router.push('/');//无用户信息，退回首页
      this.isLoading = false;
      return;
    }

    if (this.defaultConversationId === 0 || this.scriptId === 0) {
      alert('请选择剧本重新开始游戏或继续游戏。');
      this.$router.push('/');//非正常进入，退回首页
      this.isLoading = false;
      return;
    }
    try {
      await this.fetchUserConversations();//读取历史会话
      //加载当前窗口的历史消息，如果没有则初始化剧本
      await this.loadConversationMessages(this.defaultConversationId);
      if (this.windows[0].conversation.length === 0) {
        console.log("初始化剧本中");
        await this.initScript(this.defaultConversationId,this.scriptId);
      }
    } catch (error) {
      console.error("加载过程发生异常:", error);
      alert('加载异常！请刷新试试？');
    }
    //隐藏加载动画
    this.isLoading = false;
  },

  methods: {
    //切换窗口函数，切换时调用读档函数
    async selectWindow(index) {
      this.activeWindow = index;
      // 如果该窗口还没有加载过消息，则加载该对话的消息
      const selectedWindow = this.windows[this.activeWindow];
      try {
        await this.loadConversationMessages(selectedWindow.id);
        selectedWindow.loaded = true; // 标记该窗口消息已加载
      } catch (error) {
        console.error("加载对话消息失败:", error);
      }
    },
    // 读档函数，调用AIChat.js
    async loadConversationMessages(conversationId) {
      try {
        const response = await getConversationMessagesService(conversationId, this.userInfo.id);
        if(response.code === '1'){
          alert(response.message ? response.message : "读取消息失败");
          return;
        }
        if(!response.data || response.data.length === 0){
          console.log(response.message + "无对话数据");
          return;
        }
        const messages = response.data.map(msg => ({
          speaker: msg.sender === 'user' ? 'human' : 'ai',
          speech: msg.content,
        }));
        // 找到对应的对话窗口并填充消息
        const conversation = this.windows.find(window => window.id === conversationId);
        if (conversation) {
          conversation.conversation = messages;
          //AI读取历史消息
          const AiResponse = await askAIService(`${this.windows[this.activeWindow].id}`, `${this.userInfo.id}`, '加载历史消息', '1');
          if(AiResponse.code === '1'){
            console.log("AI加载对话消息失败：" + AiResponse.message);
            alert("AI加载失败，请刷新试试！");
          }
        }
      } catch (error) {
        console.error("加载对话消息失败:", error);
      }
    },
    // 获取存档函数
    async fetchUserConversations() {
      try {
        const response = await getUserConversationsService(this.userInfo.id);
        if(response.code === '1'){
          alert(response.message ? response.message : "读取会话失败");
          return;
        }
        if (!response.data) {
          console.log("没有找到历史对话！");
          return;
        }
        // 获取用户的所有对话，并逐个初始化
        for (const conv of response.data) {
          try {
            // 调用 getScriptByIdService 获取剧本信息
            const scriptResponse = await getScriptByIdService(conv.script_id);
            const conversationName = scriptResponse.data.title || "未知冒险";
            // 初始化对话数据
            const conversationData = {
              id: conv.id,
              name: conversationName,
              play_time: new Date(conv.play_time).toLocaleString(),
              conversation: [],
              loaded: false // 新对话标记为未加载
            };
            if (conv.id !== this.defaultConversationId) {
              this.windows.push(conversationData);
            }
            else{
              this.windows[0] = {  // 替换默认的第一个对话窗口
                id: this.defaultConversationId,
                name: conversationName,
                play_time: new Date(conv.play_time).toLocaleString(),
                conversation: [],
                loaded: true
              };
            }
          } catch (scriptError) {
            console.error("获取剧本信息失败:", scriptError);
          }
        }
      } catch (error) {
        console.error("获取用户历史对话或消息失败:", error);
      }
    },
    // 剧本初始化函数
    async initScript(conversationId,scriptId) {
      this.isLoading = true;
      console.log("初始化");
      try {
        // 调用AIChat.js里的初始化剧本的服务
        const response = await initializeScriptService(conversationId,scriptId);
        if(response.code === '1'){
          console.error(response.message);
          alert("剧本初始化失败，请刷新试试！");
          return;
        }
        const newMessage = {
          speaker: 'ai',
          speech: response.message // 将返回的 AI 消息添加到聊天记录
        };
        this.windows[this.activeWindow].conversation.push(newMessage);
        console.log("初始化剧本完成:", response.message);
      } catch (error) {
        console.error("初始化剧本失败:", error);
        alert("剧本初始化失败，请刷新试试！");
      } finally {
        this.isLoading = false;
      }

    },
    // 发送消息函数
    async sendMessage() {
      if (!this.message.trim()) {
        return; // 如果消息为空则不发送
      }

      // 显示加载中的动画
      this.isLoading = true;

      // 更新本地聊天记录
      const newMessage = { speaker: 'human', speech: this.message };
      this.windows[this.activeWindow].conversation.push(newMessage);
      try {
        let mes = this.message;
        this.message = '';  // 清空输入框
        // 调用AIChat.js里的函数，访问AI
        const response = await askAIService(String(this.windows[this.activeWindow].id), String(this.userInfo.id), mes, '0');
        if(response.code === '1'){
          console.log("AI回复出错：" + response.message);
          alert("AI回复出错，请刷新试试！");
          return;
        }
        const aiResponse = { speaker: 'ai', speech: response.message };
        //const aiResponse = { speaker: 'ai', speech: "response.message" };
        console.log(aiResponse);
        this.windows[this.activeWindow].conversation.push(aiResponse);
      } catch (error) {
        console.error("发送消息失败:", error);
        alert("AI回复出错，请刷新试试！");
      } finally {
        //隐藏加载动画
        this.isLoading = false;
      }
    }
  },

};
</script>

<style scoped>

#chat-app {
  display: flex;
  height: 100vh;
  background-color: #0a0a0a;
  color: #e0e0e0;
  font-family: Arial, sans-serif;
}

.loading-spinner {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.sidebar {
  width: 240px;
  background-color: #252525;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.sidebar-title {
  font-size: 1.4em;
  color: #ffcd00;
  margin-bottom: 20px;
}

.nav-list {
  list-style: none;
  padding: 0;
  margin: 0;
  flex-grow: 1;
  overflow-y: auto;
  align-items: flex-start;
}

.nav-list::-webkit-scrollbar {
  width: 8px;
}

.nav-list::-webkit-scrollbar-thumb {
  background-color: #ffcd00;
  border-radius: 10px;
  border: 2px solid #252525;
}

.nav-list::-webkit-scrollbar-track {
  background-color: #252525;
  border-radius: 10px;
}

.nav-item {
  padding: 15px;
  font-size: 1.1em;
  cursor: pointer;
  color: #bbb;
  border-radius: 8px;
  margin-bottom: 10px;
  transition: background-color 0.3s;
}

.nav-item:hover,
.nav-item.active {
  background-color: #3a3a3a;
  color: #fff;
}

.nav-item-content {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.nav-item-name {
  text-align: left;
  flex: 1;
}

.nav-item-time {
  text-align: right;
  flex: 0;
  color: #666;
  font-size: 0.9em;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #1e1e1e;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px;
  background-color: #3a3a3a;
  border-bottom: 1px solid #444;
}

.header-title {
  font-size: 1.3em;
  color: #ffcd00;
  text-align: center;
}

.send-button {
  background: none;
  border: none;
  color: #ffcd00;
  cursor: pointer;
  transition: color 0.3s;
}

.send-button:hover {
  color: #ffd633; /* 悬停时略微更亮 */
}

.chat-window {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.examples {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
  color: #ddd;
}

.example-button {
  background-color: #3a3a3a;
  color: #f0f0f0;
  border: none;
  padding: 12px;
  margin-top: 10px;
  border-radius: 8px;
  font-size: 1em;
  cursor: pointer;
}

.example-button:hover {
  background-color: #505050;
}



.chat-log .message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  width: 100%;
}

.message.ai {
  flex-direction: row;

}

.message.human {
  flex-direction: row-reverse;

}

.avatar-container {
  display: flex;
  align-items: center;
}

.message.ai .avatar-container {
  margin-right: 10px;
  margin-left: 0;
}

.message.human .avatar-container {
  margin-left: 10px;
  margin-right: 0;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.message.human .avatar {
  margin-right: 5px;
  margin-left: 0;
}
.message.ai .avatar {
  margin-right: 0;
  margin-left: 5px;
}

.nickname {
  font-weight: bold;
  color: #fff;
}

.message-text {
  padding: 12px;
  border-radius: 10px;
  color: #f5f5f5;
  max-width: 75%;
  font-size: 1em;
  word-wrap: break-word;
  white-space: pre-wrap;
  text-align: left;
}

.message.ai .message-text {
  background-color: #565656;
}

.message.human .message-text {
  background-color: #4a4a4a;
}


.input-area {
  display: flex;
  align-items: center;
  padding: 15px;
  border-top: 1px solid #444;
  background-color: #3a3a3a;
}

.input-box {
  flex: 1;
  background-color: #4d4d4d;
  color: #e0e0e0;
  padding: 12px;
  border: none;
  border-radius: 8px;
  resize: none;
  font-size: 1em;
}

.send-button .icon {
  fill: #ffcd00; /* 设置图标颜色为黄色 */
  width: 24px; /* 设置图标大小 */
  height: 24px;
}

.home-link {
  display: block;
  padding: 15px;
  font-size: 1.1em;
  color: #bbb;
  border-radius: 8px;
  text-decoration: none;
  transition: background-color 0.3s;
  margin-top: auto;
}

.home-link:hover {
  background-color: #3a3a3a;
  color: #fff;
  margin-top: auto;
}

</style>
